# -*- coding: utf-8 -*-
# @Time    : 2021/10/22 16:33
# @Author  : huangwei
# @File    : img_function2.py
# @Software: PyCharm

import cv2
import numpy as np

filepath = "images/sim.png"
src = cv2.imread(filepath)  # 默认bgr通道
# cv2.namedWindow("input", cv2.WINDOW_AUTOSIZE)
# cv2.imshow("input", src)
"""
提取图中的蓝色部分
"""
low_list = [0, 11, 26, 35, 78, 100, 125, 156]
# high_list = [10, 25, 34, 77, 99, 124, 155, 180]
high_list = [124, 155, 180]
hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)  # BGR转HSV
# low_hsv = np.array([100, 43, 46])  # 这里要根据HSV表对应，填入三个min值（表在下面）
low_hsv = np.array([low_list[5], 43, 46])  # 这里要根据HSV表对应，填入三个min值（表在下面）
# high_hsv = np.array([124, 255, 255])  # 这里填入三个max值

for k in range(len(high_list)):
    high_hsv = np.array([high_list[k], 255, 255])  # 这里填入三个max值
    mask = cv2.inRange(hsv, lowerb=low_hsv, upperb=high_hsv)  # 提取掩膜
    h, w = src.shape[0:2]
    for m in range(h):
        for n in range(w):
            if mask[m][n] == 0:
                mask[m][n] = 255
            else:
                mask[m][n] = 0

    cv2.imshow('mask{}'.format(k), mask)

# 黑色背景转透明部分
mask_contrary = mask.copy()
mask_contrary[mask_contrary == 0] = 1
mask_contrary[mask_contrary == 255] = 0  # 把黑色背景转白色
mask_bool = mask_contrary.astype(bool)
mask_img = cv2.add(src, np.zeros(np.shape(src), dtype=np.uint8), mask=mask)
# 这个是把掩模图和原图进行叠加，获得原图上掩模图位置的区域
mask_img = cv2.cvtColor(mask_img, cv2.COLOR_BGR2BGRA)
mask_img[mask_bool] = [255, 255, 255, 255]
# 这里如果背景本身就是白色，可以不需要这个操作，或者不需要转成透明背景就不需要这里的操作


# cv2.imshow("image", mask_img)
cv2.imwrite('label123.png', mask_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
